import docx
import re
import typer

app = typer.Typer(help="Contract summary tool.")


def search_file(filename: str, pattern: str):
    """Search specific information in appointed file."""
    txt = get_content(filename)
    search(txt, re.compile(pattern))


def search(txt: str, pattern: re.Pattern):
    """Use regex to match the target."""
    match = pattern.search(txt)
    if match:
        print(match.group(2))
    else:
        print("未找到")


def get_content(filename: str):
    '''get the content of docx file return the string'''
    doc = docx.Document(filename)
    txt = ""
    for p in doc.paragraphs:
        txt += p.text
    return txt


@app.command()
def output(filename: str):
    '''output the content of file into terminal'''
    print(get_content(filename))


@app.command()
def payment(filename: str, index: int = -1):
    '''retrieve the payment'''
    txt = get_content(filename)
    pattern = r"(?<=¥)(.*?)(?=元)"
    match = re.findall(pattern, txt)
    if match:
        if index != -1:
            print(match[index])
        else:
            print(match)
    else:
        print("未找到")


@app.command()
def project_name(filename: str):
    '''retrieve the project name'''
    search_file(filename, r"(项目名称：)(.*?)(   )")


@app.command()
def trustee(filename: str):
    '''retrieve the trustee'''
    search_file(filename, r"(受托方：)(.*?)(   )")


@app.command()
def client(filename: str):
    '''retrieve the client'''
    search_file(filename, r"(委托方：)(.*?)(   )")


@app.command()
def copy_amount(filename: str):
    '''retrieve the copy amount'''
    search_file(filename, r"(一式)(.*?)(份)")


if __name__ == "__main__":
    app()
